package com.lightjet.macross.base.awf.controller;

import com.lightjet.macross.base.awf.dto.ProcDefDTO;
import com.lightjet.macross.base.awf.dto.TaskStaticDTO;
import com.lightjet.macross.base.awf.service.ProcessService;
import com.lightjet.macross.base.awf.dto.TaskInstDTO;
import com.lightjet.macross.base.feign.api.controller.PrincipalController;
import com.lightjet.macross.base.feign.api.domain.AuthUser;
import com.lightjet.macross.base.feign.api.service.upms.UPMSDataMappingService;
import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.FormatUtil;
import com.lightjet.macross.common.util.RespUtil;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.java.Log;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/his")
@Scope("request")
@Log
@Api(tags="AWF业务流程服务-历史产看相关接口集")
public class HistoricalController extends PrincipalController {

    @Resource
    private ProcessService processService;

    @Resource
    private UPMSDataMappingService upmsDataMappingService;

    @RequestMapping(value = "/audit", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value ="流程审批历史接口", notes = "根据流程运行实例ID获取审批记录，返回Map Key：taskId,nodename,opdate,comments,executor")
    public ResponseDTO<List<HashMap>> AuditHistory(
            @ApiParam(name = "piid", value = "流程实例ID",required =true) String piid)
    {
        return RespUtil.CreateOK(processService.GetProcessAuditHistoryByPIID(piid));
    }

    //获取我的任务，按节点名称汇总
    @RequestMapping(value = "/audit/task", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value ="流程审批历史(TaskID)接口", notes = "根据流程任务ID获取审批记录，返回Map Key：taskId,nodename,opdate,comments,executor")
    public ResponseDTO<List<HashMap>> AuditHistoryByTaskId(
            @ApiParam(name = "id", value = "流程任务ID",required =true) String id)
    {
        return RespUtil.CreateOK(processService.GetProcessAuditHistory(id));
    }


    @RequestMapping(value="/process", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value ="流程处理情况接口", notes = "根据流程运行实例ID获取流程运行信息（包括历史处理及待处理）")
    public ResponseDTO<List<TaskInstDTO>> ProcessHistory(
            @ApiParam(name = "piid", value = "流程实例ID",required =true) String piid) {
        List<TaskInstDTO> list = processService.GetTaskHistory(piid);
        for(TaskInstDTO item :list)
        {
            try {
                item.setAsssignee(upmsDataMappingService.FindUserById(item.getAsssignee()).getDisplayname());
            }
            catch (Exception e)
            {
                log.info("根据人员ID获取名称失败：[UPMSDataMappingService]:"+e.getMessage());
            }
        }
        return RespUtil.CreateOK(list);
    }

    @RequestMapping(value="/static/task", method = {RequestMethod.POST})
    @ApiOperation(value ="流程任务节点统计接口", notes = "根据流程定义Key是否结束标识及标准节点集合（流程汇总数据据此进行匹配）获取流程节点的汇总信息")
    public ResponseDTO<List<TaskStaticDTO>> TaskStatic(
            @ApiParam(name = "staticinfo", value = "流程标准节点集合HashMap<String,Object> : {basicnodes:[\"\",\"...\"],pdkey:\"流程定义ket\",finished:false}") @RequestBody HashMap<String,Object> staticinfo)
    {
        List<String> nodes = (List<String>)staticinfo.get("basicnodes");
        if(nodes==null || nodes.size()==0)
        {
            return RespUtil.CreateOK(processService.GetTaskStatic(staticinfo.get("pdkey").toString(),(boolean)staticinfo.get("finished")));
        }
        else
        {

            List<TaskStaticDTO> list = processService.GetTaskStatic(staticinfo.get("pdkey").toString(),(boolean)staticinfo.get("finished"));
            return RespUtil.CreateOK(nodes.stream().map(e-> list.stream().filter(x->e.equals(x.getTaskname())).findFirst().orElse(new TaskStaticDTO(e,0L,0,0))).collect(Collectors.toList()));
/*            for(String task : nodes)
            {
                if(list.stream().findAny().orElse(null) == null)
                {

                }
            }*/
        }
    }

    @RequestMapping(value="/process", method = {RequestMethod.DELETE})
    @ApiOperation(value ="流程批量删除接口", notes = "根据流程运行实例ID（多个以,分割）删除流程所有相关信息")
    public ResponseDTO<String> DeleteProcess(
            @ApiParam(name = "piid_cs", value = "流程实例ID,多个以,分割",required = true) String piid_cs,
            @ApiParam(name = "reason", value = "删除原因") String reason)
    {
        return RespUtil.FromResultDTO(processService.DeleteProcess(Arrays.stream(piid_cs.split(",")).collect(Collectors.toList()), reason));
    }

    @PostMapping(value="/tasksmap",consumes = "application/json")
    @ApiOperation(value ="流程任务历史查询接口", notes = "根据流程运行实例ID列表Json获取相应以流程实例为Key的任务清单为Value的Map")
    public ResponseDTO<Map<String,List<TaskInstDTO>>> GetMappedTaskHis(@ApiParam(name = "query",value = "流程实例ID列表",required = true,type = "body") @RequestBody List<String> piids){
        return RespUtil.CreateOK(processService.GetMappedTaskHisByPIIDs(piids));
    }

    @PostMapping("/process/summary/keylist")
    @ApiOperation(value ="流程任务历史汇总信息查询接口", consumes = "application/json", notes = "根据人员ID、查询时间段及流程Key集合查询范围内的历史流程处理流程汇总信息")
    public ResponseDTO<List<ProcDefDTO>> ProcessHisotrySummary(
            @ApiParam(name = "sdate", value = "查询起始时间") String sdate,
            @ApiParam(name = "edate", value = "查询结束时间") String edate,
            @ApiParam(name = "userid", value = "用户ID") String userid,
            @ApiParam(name = "pdkeys", value = "流程定义Key集合",type="body") @RequestBody List<String> pdkeys,
            @ApiIgnore @ModelAttribute("CurrentUser") AuthUser user)
    {
        Date sd = FormatUtil.GetDefaultDateFromStr(sdate);
        Date ed = FormatUtil.GetDefaultDateFromStr(edate);
        userid = StringUtil.isNullOrEmpty(userid)? user.getId(): userid;
        return RespUtil.CreateOK( (pdkeys == null || pdkeys.size() == 0) ?processService.GetHistorySummary(userid, sd,ed)
                :processService.GetHistorySummary(userid,pdkeys,sd,ed));
    }

    @PostMapping("/process/list")
    @ApiOperation(value ="流程历史实例查询接口", consumes = "application/json",notes = "根据人员ID、查询时间段及流程定义ID（封装程map Json）查询范围内的历史流程处理流程实例列表信息")
    public ResponseDTO<List<HashMap<String,String>>> ProcessHisotryList(
            @ApiParam(name = "sdate", value = "查询条件Map Json（应包含key：pdid、sdate、edate、pageindex、pagesize）", type="body") @RequestBody HashMap<String,String> query,
            @ApiIgnore @ModelAttribute("CurrentUser") AuthUser user){

        String pdid = query.get("pdid");
        query.remove("pdid");
        Date sdate = query.containsKey("sdate")?FormatUtil.GetDefaultDateFromStr(query.get("sdate")):FormatUtil.GetDefaultDateFromStr("2000-01-01");
        query.remove("sdate");
        Date edate = query.containsKey("edate")?FormatUtil.GetDefaultDateFromStr(query.get("edate")):FormatUtil.GetDefaultDateFromStr("2999-01-01");
        query.remove("edate");
        Integer pageindex = query.containsKey("pageindex")?Integer.parseInt(query.get("pageindex")):-1;
        query.remove("pageindex");
        Integer pagesize = query.containsKey("pagesize")?Integer.parseInt(query.get("pagesize")):-1;
        query.remove("pagesize");
        return RespUtil.CreateOK(pageindex==-1? processService.GetHistoryBizTaskByQuery(user.getId(),pdid,sdate,edate,query):
                processService.GetHistoryBizTaskByQuery(user.getId(),pdid,sdate,edate,query,pageindex,pagesize));
    }

/*    @RequestMapping(value="/process/task", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value ="流程处理情况（任务ID版）接口", notes = "根据流程任务ID获取流程运行信息（包括历史处理及待处理）")
    public ResponseDTO<List<TaskInstDTO>> ProcessHistoryByTaskId(
            @ApiParam(name = "id", value = "任务ID",required =true) String id) {
        String piid = processService.GetProcInstanceIdByTid(id);
        List<TaskInstDTO> list = processService.GetTaskHistory(piid);
        for(TaskInstDTO item :list)
        {
            try {
                item.setAsssignee(upmsDataMappingService.FindUserById(item.getAsssignee()).getDisplayname());
            }
            catch (Exception e)
            {
                log.info("根据人员ID获取名称失败：[UPMSDataMappingService]:"+e.getMessage());
            }
        }
        return RespUtil.CreateOK(list);
    }*/
}
